#!/usr/bin/env bash
set -euo pipefail

# 用法: build_ios_ipa.sh <buildType> <projectPath> <unityPath> [exportOptionsPlist]
# 说明: 使用 xcodebuild archive（并在提供导出配置时 exportArchive）生成 ipa，
#       参考备份脚本，避免手动 zip 打包。

buildType="${1:-}"
projectPath="${2:-}"
unity="${3:-}"
exportOptionsPlist="${4:-}"

if [[ -z "$buildType" || -z "$projectPath" || -z "$unity" ]]; then
  echo "用法: $0 <buildType> <projectPath> <unityPath> [exportOptionsPlist]" >&2
  echo "示例: $0 RELEASE /Users/xxx/MyUnityProj /Applications/Unity/Hub/Editor/2022.3.61f1c1/Unity.app/Contents/MacOS/Unity /path/to/ExportOptions.plist" >&2
  exit 1
fi

echo "BuildType: $buildType"
echo "ProjectPath: $projectPath"
echo "Unity: $unity"
archiveRoot="$projectPath/Build/IOS/$buildType"
archivePath="$archiveRoot/app_archive"
exportPath="$archiveRoot/export"
ipaPath="$projectPath/Build/IOS/$buildType.ipa"
echo "ArchivePath: $archivePath.xcarchive"
echo "ExportPath: $exportPath (当提供 exportOptionsPlist 时导出)"

# Xcode 工程目录（Unity 导出）
projDir="$projectPath/Build/IOS/$buildType/output_xcode"
proj="$projDir/Unity-iPhone.xcodeproj"
if [[ ! -d "$proj" ]]; then
  echo "未找到 Xcode 工程: $proj" >&2
  exit 1
fi

# 配置：DEBUG -> Debug，其他 -> Release
configName="Release"
if [[ "${buildType^^}" == "DEBUG" ]]; then
  configName="Debug"
fi

# 清理与归档（使用通用 iOS 目的地）
echo "清理工程..."
xcodebuild clean -project "$proj" -scheme Unity-iPhone -configuration "$configName" -destination 'generic/platform=iOS'

echo "开始归档..."
rm -rf "$archivePath.xcarchive"
set +e
xcodebuild archive -project "$proj" -scheme Unity-iPhone -configuration "$configName" -archivePath "$archivePath" -destination 'generic/platform=iOS'
archiveStatus=$?
set -e
if [[ $archiveStatus -eq 0 && -d "$archivePath.xcarchive" ]]; then
  echo "归档完成: $archivePath.xcarchive"
else
  echo "归档失败或未生成 .xcarchive，回退为直接打包 IPA。"
  # Fallback: 构建 .app 并手动打包 IPA
  appRoot="$projDir/build/${configName}-iphoneos"
  xcodebuild build -project "$proj" -scheme Unity-iPhone -configuration "$configName" -sdk iphoneos -destination 'generic/platform=iOS'
  if [[ ! -d "$appRoot" ]]; then
    echo "未找到构建目录: $appRoot" >&2
    exit 1
  fi
  appPath=""
  if [[ -d "$appRoot/Unity-iPhone.app" ]]; then
    appPath="$appRoot/Unity-iPhone.app"
  else
    appPath=$(find "$appRoot" -maxdepth 1 -type d -name "*.app" | head -n1 || true)
  fi
  if [[ -z "$appPath" || ! -d "$appPath" ]]; then
    echo "未找到 .app 产物于: $appRoot" >&2
    exit 1
  fi
  echo "App: $appPath"
  pkgTmp="$projDir/package_tmp"
  rm -rf "$pkgTmp"
  mkdir -p "$pkgTmp/Payload"
  cp -R "$appPath" "$pkgTmp/Payload/"
  (cd "$pkgTmp" && zip -qry "$ipaPath" Payload)
  echo "IPA 已生成(回退路径): $ipaPath"
  exit 0
fi

# 可选导出 IPA
if [[ -n "${exportOptionsPlist:-}" && -f "$exportOptionsPlist" ]]; then
  echo "开始导出 IPA..."
  rm -rf "$exportPath"
  mkdir -p "$exportPath"
  xcodebuild -exportArchive -archivePath "$archivePath.xcarchive" -exportPath "$exportPath" -exportOptionsPlist "$exportOptionsPlist"
  echo "导出完成: $exportPath"
else
  echo "未提供 exportOptionsPlist，跳过导出 IPA，仅生成 .xcarchive。"
fi
